package com.warrior.gatherclient.service.impl;

import com.warrior.gatherclient.grpc.Messages;
import com.warrior.gatherclient.service.SystemInfoService;
import com.warrior.gatherclient.util.CommonUtil;
import com.warrior.gatherclient.service.GlobalMemoryService;
import com.warrior.gathercommon.constants.CommonStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;

/**
 * @ClassName GlobalMemoryServiceImpl.java
 * @Author xujian
 * @Description
 * @CreateTime 2020年12月28日 10:48:00
 */
@Service
@Slf4j
public class GlobalMemoryServiceImpl implements GlobalMemoryService {

    @Autowired
    private SystemInfoService systemInfoService;

    @Override
    public String getServiceKey() {
        return CommonStatus.CONSTANT_GLOBALMEMORY;
    }

    @Override
    public Messages.Builder execute() {
        SystemInfo systemInfo = systemInfoService.getSystemInfo();
        Messages.Builder messages =  CommonUtil.initMessage(CommonStatus.CONSTANT_GLOBALMEMORY);
        GlobalMemory memory = systemInfo.getHardware().getMemory();
        //总共内存
        Messages.Metric.Builder totalBuilder = Messages.Metric.newBuilder();
        totalBuilder.setMetricName(CommonStatus.CONSTANT_GLOBALMEMORY_TOTAL);
        totalBuilder.setMetricVaule(CommonUtil.formatByte(memory.getTotal()));
        messages.addMetrics(totalBuilder);

        //剩余内存
        Messages.Metric.Builder freeBuilder = Messages.Metric.newBuilder();
        freeBuilder.setMetricName(CommonStatus.CONSTANT_GLOBALMEMORY_AVAILABLE);
        freeBuilder.setMetricVaule(CommonUtil.formatByte(memory.getAvailable()));
        messages.addMetrics(freeBuilder);

        //已用内存
        Messages.Metric.Builder usedBuilder = Messages.Metric.newBuilder();
        usedBuilder.setMetricName(CommonStatus.CONSTANT_GLOBALMEMORY_USED);
        usedBuilder.setMetricVaule(CommonUtil.formatByte(memory.getTotal() - memory.getAvailable()));
        messages.addMetrics(usedBuilder);

        return messages;
    }
}
